<template>
  <div class="order-management-container agri-page-container">
    <div class="page-header agri-page-header">
      <div class="page-title agri-page-title">
        <el-icon><List /></el-icon>
        <span>订单管理</span>
      </div>
    </div>

    <!-- 订单筛选 -->
    <el-card class="filter-card agri-card">
      <div class="filter-form">
        <el-form :inline="true" :model="filterForm" class="demo-form-inline">
          <el-form-item label="订单状态">
            <el-select v-model="filterForm.status" placeholder="全部状态" clearable>
              <el-option label="待支付" value="pending" />
              <el-option label="待发货" value="paid" />
              <el-option label="已发货" value="shipped" />
              <el-option label="已完成" value="completed" />
              <el-option label="已取消" value="cancelled" />
            </el-select>
          </el-form-item>
          <el-form-item label="订单日期">
            <el-date-picker
              v-model="filterForm.dateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="YYYY-MM-DD"
            />
          </el-form-item>
          <el-form-item label="订单编号">
            <el-input v-model="filterForm.orderNumber" placeholder="请输入订单编号" clearable />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">
              <el-icon><Search /></el-icon> 搜索
            </el-button>
            <el-button @click="resetFilter">
              <el-icon><Refresh /></el-icon> 重置
            </el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-card>

    <!-- 订单列表 -->
    <el-card class="order-list-card agri-card" v-loading="loading">
      <div class="agri-table-wrapper">
        <el-table :data="pagedOrders" style="width: 100%">
          <el-table-column prop="orderNumber" label="订单编号" min-width="120" />
          <el-table-column prop="createdAt" label="下单时间" min-width="120" />
          <el-table-column prop="total" label="订单金额" min-width="100">
            <template #default="scope">
              ¥{{ scope.row.total ? scope.row.total.toFixed(2) : (scope.row.totalAmount ? scope.row.totalAmount.toFixed(2) : '0.00') }}
            </template>
          </el-table-column>
          <el-table-column prop="status" label="订单状态" min-width="100">
            <template #default="scope">
              <el-tag :type="getOrderStatusType(scope.row.status)">
                {{ getOrderStatusText(scope.row.status) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="220" fixed="right">
            <template #default="scope">
              <div class="agri-operations">
                <el-button type="primary" size="small" @click="viewOrderDetail(scope.row)">详情</el-button>
                <el-button v-if="scope.row.status === 'pending'" type="success" size="small" @click="payOrder(scope.row)">支付</el-button>
                <el-button v-if="['pending', 'paid'].includes(scope.row.status)" type="danger" size="small" @click="cancelOrder(scope.row)">取消</el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
      
      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          background
          layout="prev, pager, next, jumper, total"
          :total="filteredOrders.length"
          :page-size="pageSize"
          :current-page="currentPage"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 订单详情对话框 -->
    <div class="agri-dialog-wrapper">
      <el-dialog
        v-model="orderDetailVisible"
        title="订单详情"
        width="700px"
      >
        <div v-if="currentOrder" class="order-detail">
          <el-descriptions :column="2" border>
            <el-descriptions-item label="订单编号">{{ currentOrder.orderNumber }}</el-descriptions-item>
            <el-descriptions-item label="下单日期">{{ formatDate(currentOrder.orderDate) }}</el-descriptions-item>
            <el-descriptions-item label="农户名称">{{ currentOrder.farmerName }}</el-descriptions-item>
            <el-descriptions-item label="联系方式">{{ currentOrder.farmerPhone }}</el-descriptions-item>
            <el-descriptions-item label="商品名称">{{ currentOrder.productName }}</el-descriptions-item>
            <el-descriptions-item label="商品数量">{{ currentOrder.quantity }} {{ currentOrder.unit }}</el-descriptions-item>
            <el-descriptions-item label="单价">¥{{ currentOrder.price }}/{{ currentOrder.unit }}</el-descriptions-item>
            <el-descriptions-item label="总金额">¥{{ currentOrder.totalAmount }}</el-descriptions-item>
            <el-descriptions-item label="状态">
              <el-tag :type="getOrderStatusType(currentOrder.status)">
                {{ getOrderStatusText(currentOrder.status) }}
              </el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="支付方式">{{ currentOrder.paymentMethod || '未支付' }}</el-descriptions-item>
            <el-descriptions-item label="收货地址" :span="2">{{ currentOrder.address }}</el-descriptions-item>
            <el-descriptions-item label="订单备注" :span="2">{{ currentOrder.note || '无' }}</el-descriptions-item>
          </el-descriptions>

          <!-- 物流信息 -->
          <div v-if="currentOrder.logistics" class="logistics-info">
            <h3>物流信息</h3>
            <el-descriptions :column="2" border>
              <el-descriptions-item label="物流公司">{{ getLogisticsCompanyName(currentOrder.logistics.company) }}</el-descriptions-item>
              <el-descriptions-item label="物流单号">{{ currentOrder.logistics.trackingNumber }}</el-descriptions-item>
              <el-descriptions-item label="发货时间">{{ formatDate(currentOrder.shipDate) }}</el-descriptions-item>
              <el-descriptions-item label="备注">{{ currentOrder.logistics.note || '无' }}</el-descriptions-item>
            </el-descriptions>
          </div>
          
          <div class="order-timeline">
            <h3>订单状态更新</h3>
            <el-timeline>
              <el-timeline-item
                v-for="(activity, index) in orderTimeline"
                :key="index"
                :timestamp="activity.timestamp"
                :type="activity.type"
                :color="activity.color"
              >
                {{ activity.content }}
              </el-timeline-item>
            </el-timeline>
          </div>
          
          <div v-if="currentOrder.status === 'pending'" class="order-actions">
            <el-button type="success" @click="handlePayOrder(currentOrder)">立即付款</el-button>
            <el-button type="danger" @click="handleCancelOrder(currentOrder)">取消订单</el-button>
          </div>
          
          <div v-if="currentOrder.status === 'shipped'" class="order-actions">
            <el-button type="success" @click="handleConfirmReceipt(currentOrder)">确认收货</el-button>
          </div>
        </div>
      </el-dialog>
    </div>
    
    <!-- 付款对话框 -->
    <el-dialog
      v-model="paymentDialogVisible"
      title="订单付款"
      width="500px"
    >
      <div v-if="currentOrder" class="payment-dialog">
        <div class="payment-info">
          <h3>订单信息</h3>
          <p>订单编号：{{ currentOrder.orderNumber }}</p>
          <p>商品名称：{{ currentOrder.productName }}</p>
          <p>订单金额：<span class="payment-amount">¥{{ currentOrder.totalAmount }}</span></p>
        </div>
        
        <el-divider />
        
        <div class="payment-method">
          <h3>选择支付方式</h3>
          <el-radio-group v-model="paymentMethod">
            <el-radio label="wechat">微信支付</el-radio>
            <el-radio label="alipay">支付宝</el-radio>
            <el-radio label="bank">银行转账</el-radio>
          </el-radio-group>
        </div>
        
        <div class="payment-qrcode" v-if="paymentMethod">
          <div class="qrcode-container">
            <img :src="getPaymentQRCode()" alt="支付二维码" class="qrcode-image" />
          </div>
          <p class="qrcode-tip">请使用{{ getPaymentMethodText() }}扫描二维码完成支付</p>
        </div>
      </div>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="paymentDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmPayment" :loading="paymentLoading">
            确认已支付
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, watch, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import { List, Plus, Search, Refresh } from '@element-plus/icons-vue';
import { useBuyerStore } from '../../store';
import { format } from 'date-fns';

// 路由和状态管理
const router = useRouter();
const buyerStore = useBuyerStore();

// 列表和分页
const loading = ref(false);
const orders = ref([]);
const currentPage = ref(1);
const pageSize = ref(10);
const activeTab = ref('all');

// 订单详情相关
const orderDetailVisible = ref(false);
const currentOrder = ref(null);

// 支付相关
const paymentDialogVisible = ref(false);
const paymentMethod = ref('');
const paymentLoading = ref(false);

// 筛选表单
const filterForm = reactive({
  status: '',
  dateRange: [],
  orderNumber: ''
});

// 监听标签页变化更改筛选条件
watch(activeTab, (newValue) => {
  if (newValue === 'all') {
    filterForm.status = '';
  } else {
    filterForm.status = newValue;
  }
});

// 订单按状态和筛选条件过滤
const filteredOrders = computed(() => {
  let result = [...orders.value];
  
  // 按状态过滤
  if (filterForm.status) {
    result = result.filter(order => order.status === filterForm.status);
  }
  
  // 按订单号过滤
  if (filterForm.orderNumber) {
    result = result.filter(order => 
      order.orderNumber.toLowerCase().includes(filterForm.orderNumber.toLowerCase())
    );
  }
  
  // 按日期范围过滤
  if (filterForm.dateRange && filterForm.dateRange.length === 2) {
    const [startDate, endDate] = filterForm.dateRange;
    result = result.filter(order => {
      const orderDate = new Date(order.orderDate).toISOString().split('T')[0];
      return orderDate >= startDate && orderDate <= endDate;
    });
  }
  
  return result;
});

// 分页后的订单
const pagedOrders = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value;
  const end = start + pageSize.value;
  return filteredOrders.value.slice(start, end);
});

// 订单时间线
const orderTimeline = computed(() => {
  if (!currentOrder.value) return [];
  
  const timeline = [];
  
  // 创建订单
  timeline.push({
    content: '订单创建',
    timestamp: formatDate(currentOrder.value.orderDate),
    type: 'primary',
    color: '#409EFF'
  });
  
  // 支付订单
  if (['paid', 'shipped', 'completed'].includes(currentOrder.value.status)) {
    timeline.push({
      content: '订单支付',
      timestamp: formatDate(currentOrder.value.paymentDate || currentOrder.value.orderDate),
      type: 'success',
      color: '#67C23A'
    });
  }
  
  // 发货
  if (['shipped', 'completed'].includes(currentOrder.value.status)) {
    timeline.push({
      content: '商品发货',
      timestamp: formatDate(currentOrder.value.shipDate),
      type: 'info',
      color: '#909399'
    });
  }
  
  // 完成
  if (currentOrder.value.status === 'completed') {
    timeline.push({
      content: '订单完成',
      timestamp: formatDate(currentOrder.value.completeDate),
      type: 'success',
      color: '#67C23A'
    });
  }
  
  // 取消
  if (currentOrder.value.status === 'cancelled') {
    timeline.push({
      content: '订单取消',
      timestamp: formatDate(currentOrder.value.cancelDate || currentOrder.value.orderDate),
      type: 'danger',
      color: '#F56C6C'
    });
  }
  
  return timeline;
});

// 获取订单状态类型
const getOrderStatusType = (status) => {
  const types = {
    'pending': 'warning',
    'paid': 'primary',
    'shipped': 'info',
    'completed': 'success',
    'cancelled': 'danger'
  };
  return types[status] || 'info';
};

// 获取订单状态文本
const getOrderStatusText = (status) => {
  const texts = {
    'pending': '待支付',
    'paid': '待发货',
    'shipped': '已发货',
    'completed': '已完成',
    'cancelled': '已取消'
  };
  return texts[status] || '未知状态';
};

// 获取物流公司名称
const getLogisticsCompanyName = (code) => {
  const companies = {
    'SF': '顺丰速运',
    'ZTO': '中通快递',
    'YTO': '圆通速递',
    'YD': '韵达快递',
    'STO': '申通快递',
    'other': '其他'
  };
  return companies[code] || code;
};

// 格式化日期
const formatDate = (date) => {
  if (!date) return '';
  return format(new Date(date), 'yyyy-MM-dd HH:mm');
};

// 获取支付方式文本
const getPaymentMethodText = () => {
  const methods = {
    'wechat': '微信',
    'alipay': '支付宝',
    'bank': '银行APP'
  };
  return methods[paymentMethod.value] || '';
};

// 获取支付二维码
const getPaymentQRCode = () => {
  // 实际项目中应该根据支付方式和订单返回不同的二维码
  return 'https://t7.baidu.com/it/u=1956604245,3662848945&fm=193&f=GIF';
};

// 搜索订单
const handleSearch = () => {
  currentPage.value = 1;
};

// 重置筛选条件
const resetFilter = () => {
  Object.assign(filterForm, {
    status: '',
    dateRange: [],
    orderNumber: ''
  });
  activeTab.value = 'all';
  currentPage.value = 1;
};

// 分页处理
const handleSizeChange = (val) => {
  pageSize.value = val;
  currentPage.value = 1;
};

const handleCurrentChange = (val) => {
  currentPage.value = val;
};

// 跳转到创建订单页面
const navigateToCreateOrder = () => {
  router.push('/dashboard/buyer/create-order');
};

// 查看订单详情
const viewOrderDetail = async (order) => {
  loading.value = true;
  try {
    // 确保获取完整的订单信息
    const fullOrder = order;
    if (!order.orderDate || !order.statusText) {
      // 如果订单信息不完整，先尝试从 buyerStore 中获取
      const storeOrder = buyerStore.orders.find(o => o.id == order.id);
      if (storeOrder) {
        Object.assign(fullOrder, storeOrder);
      }
    }
    
    currentOrder.value = fullOrder;
    // 设置订单状态文本，以防未设置
    if (!currentOrder.value.statusText) {
      currentOrder.value.statusText = getOrderStatusText(currentOrder.value.status);
    }
    orderDetailVisible.value = true;
  } catch (error) {
    console.error('加载订单详情失败', error);
    ElMessage.error('加载订单详情失败');
  } finally {
    loading.value = false;
  }
};

// 支付订单
const payOrder = (order) => {
  currentOrder.value = order;
  paymentMethod.value = '';
  paymentDialogVisible.value = true;
};

// 取消订单
const cancelOrder = (order) => {
  handleCancelOrder(order);
};

// 确认支付
const confirmPayment = async () => {
  if (!paymentMethod.value) {
    ElMessage.warning('请选择支付方式');
    return;
  }
  
  try {
    paymentLoading.value = true;
    
    // 调用支付API
    await buyerStore.payOrder(currentOrder.value.id, {
      paymentMethod: paymentMethod.value
    });
    
    ElMessage.success('支付成功');
    paymentDialogVisible.value = false;
    orderDetailVisible.value = false;
    
    // 刷新订单列表
    fetchOrders();
  } catch (error) {
    console.error('支付失败', error);
    ElMessage.error('支付失败: ' + (error.message || '未知错误'));
  } finally {
    paymentLoading.value = false;
  }
};

// 确认收货
const handleConfirmReceipt = (order) => {
  ElMessageBox.confirm(
    '确认已收到商品？',
    '确认收货',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      await buyerStore.receiveOrder(order.id);
      ElMessage.success('确认收货成功');
      orderDetailVisible.value = false;
      fetchOrders();
    } catch (error) {
      console.error('确认收货失败', error);
      ElMessage.error('确认收货失败: ' + (error.message || '未知错误'));
    }
  }).catch(() => {});
};

// 取消订单
const handleCancelOrder = (order) => {
  console.log(`尝试取消订单: ${order.id}, 状态: ${order.status}`);
  
  // 确保订单有状态文本
  if (!order.statusText) {
    order.statusText = getOrderStatusText(order.status);
  }
  
  // 检查订单是否可以取消（pending或paid状态可以取消）
  if (order.status !== 'pending' && order.status !== 'paid') {
    ElMessage.warning(`订单状态为${order.statusText}，无法取消`);
    return;
  }
  
  // 对已支付订单给予特别提醒
  const confirmMessage = order.status === 'paid' 
    ? '此订单已支付，取消后退款将根据平台规则处理，确定要取消吗？' 
    : '确定要取消该订单吗？';
  
  ElMessageBox.confirm(
    confirmMessage,
    '取消订单',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    loading.value = true;
    try {
      console.log('用户确认取消订单，开始执行取消操作');
      const response = await buyerStore.cancelOrder(order.id);
      console.log('取消订单成功，响应:', response);
      
      ElMessage.success('订单已取消');
      orderDetailVisible.value = false;
      
      // 延迟一下再刷新订单列表，确保后端数据更新完成
      setTimeout(() => {
        fetchOrders();
      }, 500);
    } catch (error) {
      console.error('取消订单失败:', error);
      // 显示具体错误消息
      const errorMsg = error.message || '未知错误';
      ElMessage.error(`取消订单失败: ${errorMsg}`);
    } finally {
      loading.value = false;
    }
  }).catch(() => {
    console.log('用户取消了操作');
  });
};

// 获取订单列表
const fetchOrders = async () => {
  loading.value = true;
  try {
    const ordersData = await buyerStore.fetchOrders();
    
    // 确保每个订单都有statusText属性
    const processedOrders = ordersData.map(order => {
      if (!order.statusText) {
        order.statusText = getOrderStatusText(order.status);
      }
      return order;
    });
    
    orders.value = processedOrders;
    console.log('订单列表加载完成，共', orders.value.length, '条记录');
  } catch (error) {
    console.error('获取订单失败', error);
    ElMessage.error('获取订单列表失败');
  } finally {
    loading.value = false;
  }
};

// 组件挂载时获取订单列表
onMounted(() => {
  fetchOrders();
});
</script>

<style scoped>
.order-management-container {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-title {
  font-size: 22px;
  font-weight: bold;
  display: flex;
  align-items: center;
}

.page-title .el-icon {
  margin-right: 8px;
  font-size: 24px;
  color: var(--primary-color);
}

.page-actions {
  display: flex;
  align-items: center;
}

.filter-card {
  margin-bottom: 20px;
}

.filter-form {
  padding: 10px 0;
}

.order-tabs {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.order-timeline {
  margin-top: 20px;
}

.order-timeline h3 {
  margin-bottom: 15px;
  font-size: 16px;
  font-weight: bold;
}

.logistics-info {
  margin-top: 20px;
}

.logistics-info h3 {
  margin-bottom: 15px;
  font-size: 16px;
  font-weight: bold;
}

.order-actions {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.payment-info {
  margin-bottom: 20px;
}

.payment-info h3 {
  margin-bottom: 10px;
  font-size: 16px;
  font-weight: bold;
}

.payment-amount {
  color: #ff6b6b;
  font-weight: bold;
  font-size: 18px;
}

.payment-method h3 {
  margin-bottom: 10px;
  font-size: 16px;
  font-weight: bold;
}

.payment-qrcode {
  margin-top: 20px;
  text-align: center;
}

.qrcode-container {
  display: flex;
  justify-content: center;
  margin-bottom: 10px;
}

.qrcode-image {
  width: 200px;
  height: 200px;
  border: 1px solid #dcdfe6;
}

.qrcode-tip {
  color: #606266;
  font-size: 14px;
}

.empty-data {
  padding: 40px 0;
  text-align: center;
}

@media (max-width: 768px) {
  .page-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }
  
  .el-form-item {
    margin-bottom: 10px;
  }
}
</style> 